"use strict";
define(["commonUI","getTime","laydate", "template","global","select2", "datatables","nav"], function (
    commonUI, getTime,laydate,template,global
) {
    var project = null;
    var user = null;
    var standardTable1,standardTable1_2, standardTable2;
    var param1 = {
        pageNumber: 1,
        pageNumber: 10
    };
    var param2 = {
        pageNumber: 1,
        pageSize: 10
    };
    var param3 = {
        pageNumber: 1,
        pageSize: 10
    };
    var flag = true;
    var app = {
        init: function () {
            if(!global.existCurrProject()){
                alert("请先选择项目")
                return;
            }
            project = global.getCurrProject();
            user = global.getLoginUser();
            this.initText()
            this.initSysClass();
            this.eventBind();
            // getTime.resize();
            getTime.getNowDate();
            getTime.getTimeInfo();
            this.initSelect1();
            this.initTable1();
        },
        /**
        * 渲染文字内容
        */
         initText: function() {
            //用户名显示
            $(".name").text(user.userName)
        },
        //初始化系统分类
        initSysClass:function(){
            global.get("/web/om/sysClass/list/"+project.id,response=>{
                var data = response.data.sysclasses;
                var html=`
                    <label class="label-text" style="width: 84px;">系统分类:</label>
                    <label class="radio-inline radio-card chooseAll">
                        <input type="radio" name="sysClass" class="selected" value="" checked>
                        <span class="text-label">全部</span>
                    </label>
                    {{each data as val i}}
                        <label class="radio-inline radio-card">
                            <input type="radio" name="sysClass" value="{{val.id}}">
                            <span class="text-label">{{val.className}}</span>
                        </label>
                    {{/each}}
                `
                var tplHtml = template.compile(html);
                $(".sys-class").html(tplHtml({
                    "data": data,
                }));

            });
        },
        // 搜索条件初始化
        initSelect1: function () {
            var start = laydate.render({
                elem: '#beginTime',
                showBottom: false,
                eventElem: '.layout-icon-1',
                trigger: 'click',
                // max: 0,
                done: function (value, date, endDate) {
                    end.config.min = {
                        year: date.year,
                        month: date.month - 1,
                        date: date.date
                    }; 
                    end.config.value = {
                        year: date.year,
                        month: date.month - 1,
                        date: date.date
                    }; //将结束日的初始值设定为开始日
                }
            });
            //结束时间
            var end = laydate.render({
                elem: '#endTime',
                showBottom: false,
                eventElem: '.layout-icon-2',
                trigger: 'click',
                // max: 0,
                done: function (value, date) {
                    start.config.max = {
                        year: date.year,
                        month: date.month - 1,
                        date: date.date
                    }; //结束日选好后，重置开始日的最大日期
                }
    
            })
        },
        // 表格初始化
        initTable1: function () {
            if (this.standardTable1) {
                this.standardTable1.clear();
                this.standardTable1.destroy();
            }
            standardTable1 = $("#standard_table1").DataTable({
                // 关闭搜索功能
                processing: true,
                searching: false,
                serverSide: true,
                destroy: true,
                ordering: false,
                // scrollY: 600,
                // scrollCollapse: true,
                columns: [{
                    title: "序号",
                    data: "number",
                    width: "150px",
                    render: function (data, type, full) {
                        return "<div class='rank'>" + data + "</div>";
                    }
                },{
                    title: "名称",
                    data: "name",
                    width: "20%",
                    // render: function (data, type, full) {
                    //     return "<div class=\"text-overflow\"><span style='color: #ffc820;'>"+full.no+"</span>"+data+"</div>";
                    // }
                }, {
                    title: "报警时间",
                    data: "createTime",
                    width: "20%",
                    render: function(data,type,full,meta){//其中data代表本列数据，full代表本行所有数据
                        if(data=="null") {
                            return "";
                        }else{
                            return data;
                        }
                    }
                }, {
                    title: "处理人",
                    data: "userName",
                    width: "10%"
                }, {
                    title: "处理时间",
                    data: "addressTime",
                    width: "20%",
                    render: function(data,type,full,meta){//其中data代表本列数据，full代表本行所有数据
                        if(data=="null") {
                            return "";
                        }else{
                            return data;
                        }
                    }
                }, {
                    title: "处理过程",
                    data: "status",
                    width: "15%",
                    render: function(data,type,full,meta){//其中data代表本列数据，full代表本行所有数据
                        if(data==false) {
                            return "<span style='color: #ef671d'>" + "未处理" + "</span>"
                        } else {
                            return "<span style='color: #27d9d6'>" + "已处理" + "</span>"
                        }
                    }
                }, {
                    title: "操作",
                    data: "status",
                    width: "80px",
                    render: function(data,type,full,meta){
                        if(data==false) {
                            return "<button type='button' class='btn btn-warning dealData' data-id='"+full.id+"' data-name='"+full.name+"'>立即处理</button>";
                        } else {
                            return "<button type='button' class='btn btn-warning dealData' disabled>立即处理</button>";
                        }
                    }
                }],
                columnDefs:[{
                    // targets 同时制定多个列时，可以传递数组（比如[1,2]）;制定所有传"_all"  
                    targets: [1,2,3,5],
                    render: function(data,type,full,meta){//其中data代表本列数据，full代表本行所有数据
                        return "<div class=\"text-overflow\" title=\"" + data + "\">" + data + "</div>";
                    }
                }],
                language: {
                    sEmptyTable: "<div class=\"blank-icon\"><p class=\"msg\"><i class=\"aidicon aidicon-emoticon-sad\"></i> 没有搜到任何数据</p></div>"
                },
                ajax: function (params, callback, setting) {
                    param1.pageNumber = (params.start / params.length) + 1;
                    param1.pageSize = params.length;
                    param1.projectId = project.id;
                    param1.startTimeSearch = $("#beginTime").val();
                    param1.endTimeSearch = $("#endTime").val();
                    param1.keySearch = $("#optUser").val();

                    global.get("/web/om/alarm/list",function (res) {
                        if (res.success) {
                            var obj = {};
                            obj.data = res.data.page.content;
                            obj.draw = params.draw;
                            obj.recordsTotal = res.data.page.totalElements;
                            obj.recordsFiltered = res.data.page.totalElements;
                            callback(obj);
                            }
                        },param1);
                
                },
                initComplete: function (settings, json) {

                }
            });
        },
        initTable1_2: function () {
            if (standardTable1_2) {
                standardTable1_2.clear();
                standardTable1_2.destroy();
            }
            standardTable1_2 = $("#standard_table1_2").DataTable({
                // 关闭搜索功能
                processing: true,
                searching: false,
                serverSide: true,
                destroy: true,
                ordering: false,
                // scrollY: 600,
                // scrollCollapse: true,
                columns: [{
                    title: "序号",
                    data: "number",
                    width: "10%",
                    render: function (data, type, full) {
                        return "<div class='rank'>" + data + "</div>";
                    }
                },{
                    title: "监测点位",
                    data: "name",
                    width: "20%",
                    // render: function (data, type, full) {
                    //     return "<div class=\"text-overflow\"><span style='color: #ffc820;'>"+full.no+"</span>"+data+"</div>";
                    // }
                }, {
                    title: "监控时间",
                    data: "warnTime",
                    width: "20%",
                    render: function(data,type,full,meta){//其中data代表本列数据，full代表本行所有数据
                        if(data=="null") {
                            return "";
                        }else{
                            return data;
                        }
                    }
                }, {
                    title: "实时数据",
                    data: "data",
                    width: "20%",
                    render:function(data,type,full,meta){
                        return data +" "+ full.unit
                    }
                },{
                    title: "阈值",
                    data: "status",
                    width: "20%",
                    render:function(data,type,full,meta){
                        var left = "*";
                        var right = "*";
                        if(full.minThreshold != null){
                            left=full.minThreshold;
                        }
                        if(full.maxThreshold != null){
                            right=full.maxThreshold;
                        }

                        return left + "  -  "+right+" "+ full.unit
                    }
                }, {
                    title: "报警状态",
                    data: "status",
                    width: "20%",
                    render: function(data,type,full,meta){//其中data代表本列数据，full代表本行所有数据
                        if(data==0) {
                            return '<span class="label label-danger">报警</span>';
                        } else {
                            return '<span class="label label-primary">正常</span>';
                        }
                    }
                }, {
                    title: "操作",
                    data: "no",
                    width: "80px",
                    render: function(data,type,full,meta){//其中data代表本列数据，full代表本行所有数据
                            return "<button type='button' class='btn btn-warning editBtn' data-unit='"+full.unit+"' data-id='"+full.deviceId+"' data-name='"+full.name+"' data-min='"+full.minThreshold+"' data-max='"+full.maxThreshold+"'>编辑</button>";
                    }
                }],
                columnDefs:[{
                    // targets 同时制定多个列时，可以传递数组（比如[1,2]）;制定所有传"_all"  
                    targets: [1,2],
                    render: function(data,type,full,meta){//其中data代表本列数据，full代表本行所有数据
                        return "<div class=\"text-overflow\" title=\"" + data + "\">" + data + "</div>";
                    }
                }],
                language: {
                    sEmptyTable: "<div class=\"blank-icon\"><p class=\"msg\"><i class=\"aidicon aidicon-emoticon-sad\"></i> 没有搜到任何数据</p></div>"
                },
                ajax: function (params, callback, setting) {
                    param2.pageNumber = (params.start / params.length) + 1;
                    param2.pageSize = params.length;
                    param2.projectId = project.id;
                    param2.startTimeSearch = $("#beginTime").val();
                    param2.endTimeSearch = $("#endTime").val();
                    param2.keySearch = $("#optUser").val();

                    global.get("/web/om/runningwarning/list",function (res) {
                        if (res.success) {
                            var obj = {};
                            obj.data = res.data.page.content;
                            obj.draw = params.draw;
                            obj.recordsTotal = res.data.page.totalElements;
                            obj.recordsFiltered = res.data.page.totalElements;
                            callback(obj);
                            }
                        },param2);
                
                },
                initComplete: function (settings, json) {

                }
            });
        },
        // 表格初始化
        initTable2: function () {
            standardTable2 = $("#standard_table2").DataTable({
                // 关闭搜索功能
                processing: true,
                searching: false,
                serverSide: true,
                destroy: true,
                ordering: false,
                // scrollY: 600,
                // scrollCollapse: true,
                columns: [{
                    title: "序号",
                    data: "number",
                    width: "10%",
                    render: function (data, type, full) {
                        return "<div class='rank'>" + data + "</div>";
                    }
                },{
                    title: "设备名称",
                    data: "name",
                    width: "100px",
                    render: function (data, type, full) {
                        return "<div class=\"text-overflow\" title=\"" + data + "\" style='color: #ffc820;font-weight:bold;'>" + data + "</div>";
                    }
                }, {
                    title: "型号",
                    data: "modelNum",
                    width: "10%"
                }, {
                    title: "设备数量",
                    data: "maintainNumber",
                    width: "10%"
                }, {
                    title: "系统分类",
                    data: "sysclassName",
                    width: "15%"
                }, {
                    title: "春季保养",
                    data: "springMaintainDate",
                    width: "15%",
                    render: function (data, type, full) {
                        if(data!=null) {
                            return '<div>状态：<span style="color: #44e07b;">已保养</span></div><div>时间：'+data+'</div>'
                        } else {
                            return '<div>状态：<span style="color: #f36b60;">未保养</span></div>'
                        }
                    }
                }, {
                    title: "秋季保养",
                    data: "autumnMaintainDate",
                    width: "15%",
                    render: function (data, type, full) {
                        if(data!=null) {
                            return '<div>状态：<span style="color: #44e07b;">已保养</span></div><div>时间：'+data+'</div>'
                        } else {
                            return '<div>状态：<span style="color: #f36b60;">未保养</span></div>'
                        }
                    }
                }, {
                    title: "备注",
                    data: "description",
                    width: "35%"
                }, {
                    title: "操作",
                    data: "flag",
                    width: "80px",
                    render: function (data, type, full) {
                        return "<button type='button' data-id='"+full.id+"' class='btn btn-warning toDetail'>详情</button>";
                    }
                }],
                columnDefs:[{
                    // targets 同时制定多个列时，可以传递数组（比如[1,2]）;制定所有传"_all"  
                    targets: [1,2,3,4,5,7],
                    render: function(data,type,full,meta){//其中data代表本列数据，full代表本行所有数据
                        return "<div class=\"text-overflow\" title=\"" + data + "\">" + data + "</div>";
                    }
                }],
                language: {
                    sEmptyTable: "<div class=\"blank-icon\"><p class=\"msg\"><i class=\"aidicon aidicon-emoticon-sad\"></i> 没有搜到任何数据</p></div>"
                },
                ajax: function (params, callback, setting) {
                    param3.pageNumber = (params.start / params.length) + 1;
                    param3.pageSize = params.length;
                    param3.projectId = project.id;
                    param3.sysclassId = $("input.selected").val()  
                    param3.keySearch = $("#search_val").val();

                    global.get("/web/om/maintain/list",function (res) {
                        if (res.success) {
                            var obj = {};
                            obj.data = res.data.page.content;
                            obj.draw = params.draw;
                            obj.recordsTotal = res.data.page.totalElements;
                            obj.recordsFiltered = res.data.page.totalElements;
                            callback(obj);
                            }
                        },param3);
                },
                initComplete: function (settings, json) {
                    $('[data-toggle="tooltip"]').tooltip();
                }
            });
        },
        /** 事件绑定 */
        eventBind: function () {
            $(document).on("click", ".tab-nav li", function () {
                $(this).addClass("active").siblings("li").removeClass("active");
                var index = $(this).attr("type");
                $(".tab-wrapper").eq(index-1).removeClass("hidden").siblings(".tab-wrapper").addClass("hidden");
                if(flag) {
                    app.initTable2();
                    flag = false;
                }
            })
            $(document).on("click", "#searchBtn1", function () {
                // 改变param1参数
                standardTable1.ajax.reload();
            })
            //点击系统分类名称
            $(document).on("click", "input[name='sysClass']", function () {
                // 改变param2参数
                $("input[name='sysClass']").removeClass("selected")
                $(this).addClass("selected");
                standardTable2.ajax.reload();
            })
            $(document).on("click", "#searchBtn2", function () {
                // 改变param2参数
                standardTable2.ajax.reload();
            })
            $(document).on("click", ".table-tab li", function () {
                $(this).addClass("active").siblings("li").removeClass("active");
                var index = $(this).index();
                $('.tab-table-wrap').eq(index).removeClass('hidden').siblings('.tab-table-wrap').addClass('hidden');
                if(index===0) {
                    app.initTable1();
                } else{
                    app.initTable1_2();
                }
            })
            $(document).on("click", "#searchBtn1", function () {
                // 改变param1参数
                var index = $(this).attr("type");
                if(index===0) {
                    standardTable1.ajax.reload();
                } else{
                    standardTable1_2.ajax.reload();
                }
            })
            $(document).on("click", "#searchBtn2", function () {
                // 改变param2参数
                standardTable2.ajax.reload();
            })
            // 新增
            $(document).on("click", "#addBtn", function () {
                Dialog.open({
                    title: "新增",
                    theme: "formDialog",
                    width: 480,
                    height: 256,
                    context: self,
                    content: template("addFormTpl"),
                    onShow: function () {
                        $('#equipment').select2({
                            //  minimumResultsForSearch设置为-1，去除搜索框 
                            minimumResultsForSearch:-1,
                            placeholder:"请选择",
                            data: [
                                {
                                    id: 1,
                                    text: '设备1'
                                },
                                {
                                    id: 2,
                                    text: '设备2'
                                }
                            ]
                        });
                    },
                    onClosed: function () {
                        if ($("#_idlg_mask_").length > 0) {
                            $("#_idlg_mask_").remove();
                        }
                    },
                    button: [{
                        id: "mybtn1",
                        label: "确定",
                        intent: "primary",
                        focus: true,
                        click: function () {
                            
                        }
                    },
                        {
                            id: "mybtn2",
                            label: "取消",
                            intent: "default",
                            click: function () {
                                this.close();
                            }
                        }
                    ],
                });
            })
            // 立即处理--报警监测
            $(document).on("click", ".dealData", function () {
                var name=$(this).attr("data-name");
                var id=$(this).attr("data-id");
                Dialog.open({
                    title: "立即处理",
                    theme: "formDialog",
                    width: 636,
                    height: 510,
                    context: self,
                    content: template("dataFormTpl",{name,name}),
                    onShow: function () {
                        
                    },
                    onClosed: function () {
                        if ($("#_idlg_mask_").length > 0) {
                            $("#_idlg_mask_").remove();
                        }
                    },
                    button: [{
                        id: "mybtn1",
                        label: "确定",
                        intent: "primary",
                        focus: true,
                        click: function () {
                            var data = {};
                            data.alarmId=id;
                            data.userName=$("#userName").val();
                            data.result=$("#result").val();
                            global.post("/web/om/alarm/deal",response=>{
                                if(response.success){
                                    standardTable1.ajax.reload();
                                }else{
                                    alert(response.message);
                                }
                            },JSON.stringify(data))
                        }
                    },
                        {
                            id: "mybtn2",
                            label: "取消",
                            intent: "default",
                            click: function () {
                                this.close();
                            }
                        }
                    ],
                });
            })
            // 修改时间
            $(document).on("click", ".editData", function () {
                Dialog.open({
                    title: "修改保养时间",
                    theme: "formDialog",
                    width: 480,
                    height: 256,
                    context: self,
                    content: template("editFormTpl"),
                    onShow: function () {
                        laydate.render({
                            elem: '#nextTime',
                            showBottom: false,
                            eventElem: '.layout-icon-12',
                            trigger: 'click'
                        })
                    },
                    onClosed: function () {
                        if ($("#_idlg_mask_").length > 0) {
                            $("#_idlg_mask_").remove();
                        }
                    },
                    button: [{
                        id: "mybtn1",
                        label: "确定",
                        intent: "primary",
                        focus: true,
                        click: function () {
                            
                        }
                    },
                        {
                            id: "mybtn2",
                            label: "取消",
                            intent: "default",
                            click: function () {
                                this.close();
                            }
                        }
                    ],
                });
            })
            // 修改--运行报警
            $(document).on("click", ".editBtn", function () {
                var deviceId = $(this).attr("data-id");
                var data = {}
                data.name = $(this).attr("data-name");
                data.min = $(this).attr("data-min")==null || $(this).attr("data-min")=="" || $(this).attr("data-min")=="null"?"":$(this).attr("data-min");
                data.max = $(this).attr("data-max")==null || $(this).attr("data-max")=="" || $(this).attr("data-max")=="null"?"":$(this).attr("data-max");
                data.unit = $(this).attr("data-unit");
                Dialog.open({
                    title: "修改",
                    theme: "formDialog",
                    width: 480,
                    height: 300,
                    context: self,
                    content: template("editEquipTpl",{data:data}),
                    onShow: function () {
                        laydate.render({
                            elem: '#nextTime',
                            showBottom: false,
                            eventElem: '.layout-icon-12',
                            trigger: 'click'
                        })
                    },
                    onClosed: function () {
                        if ($("#_idlg_mask_").length > 0) {
                            $("#_idlg_mask_").remove();
                        }
                    },
                    button: [{
                        id: "mybtn1",
                        label: "确定",
                        intent: "primary",
                        focus: true,
                        click: function () {
                            var data = {};
                            data.minThreshold = $("#minThreshold").val();
                            data.maxThreshold = $("#maxThreshold").val();
                            global.post("/web/om/maintain/threshold/saveOrUpdate/"+deviceId + "?minThreshold="+data.minThreshold + "&maxThreshold="+data.maxThreshold,response=>{
                                if(response.success){
                                    standardTable1_2.ajax.reload();
                                }else{
                                    alert(response.message);
                                }
                            })
                        }
                    },
                        {
                            id: "mybtn2",
                            label: "取消",
                            intent: "default",
                            click: function () {
                                this.close();
                            }
                        }
                    ],
                });
            })
            // 保养流程
            $(document).on("click", "#flow", function () {
                Dialog.open({
                    title: "保养流程",
                    theme: "formDialog",
                    width: 800,
                    height: 620,
                    context: self,
                    content: template("flowTpl"),
                    onShow: function () {
                        
                    },
                    onClosed: function () {
                        if ($("#_idlg_mask_").length > 0) {
                            $("#_idlg_mask_").remove();
                        }
                    },
                    button: [{
                        id: "mybtn1",
                        label: "删除",
                        intent: "primary",
                        focus: true,
                        click: function () {
                            Dialog.open({
                                title: "<span class='aidicon aidicon-alert-circle-outline aidicon-warning'></span><span class='lineClamp2'>确认删除信息</span>",
                                width: 420,
                                height: 'auto',
                                modal: true,
                                content:'<div class="padding-left-large-5">确认需要删除保养流程吗？删除后不可恢复。</div>',
                                button: [
                                    {id:"mybtn1", label:"确认", intent:"primary", focus:true, click:function(){}},
                                    {id:"mybtn2", label:"取消", click:function(){}}
                                ]
                            });
                        }
                    },
                        {
                            id: "mybtn2",
                            label: "取消",
                            intent: "default",
                            click: function () {
                                this.close();
                            }
                        }
                    ],
                });
            })
            
            // 立即处理--设备保养
            $(document).on("click", ".delData", function () {
                Dialog.open({
                    title: "<span class='aidicon aidicon-alert-circle-outline aidicon-warning'></span><span class='lineClamp2'>确认保养该设备吗？</span>",
                    width: 420,
                    height: 169,
                    modal: true,
                    button: [
                        {id:"mybtn1", label:"确认", intent:"primary", focus:true, click:function(){}},
                        {id:"mybtn2", label:"取消", click:function(){}}
                    ]
                });
            })
            // 详情--设备保养
            $(document).on("click", ".toDetail", function () {
                var id=$(this).attr("data-id");
                window.open('detail.html?equipmentMaintainId='+id, '_blank');
            })

            // 设备保养--搜索
            $(document).on("click", "#eq-search .aidicon-magnify", function () {
                standardTable2.ajax.reload();
            })
            // 设备保养--搜索清空按钮
            $(document).on("mousedown", "#eq-search .aidicon-close", function () {
                $("#search_val").val("");
            })
            window.onresize = function () {
                // getTime.resize();
            };
             //导出报表
             $(document).on("click","#export",function(){
                window.open(global.baseUrl+"/web/om/maintain/exportInfo/"+project.id)
            })
        },
        
    };
    return app;
});